<template>
  <a-modal
    v-model:visible="modalVisible"
    title="消息通知"
    width="800px"
    :footer="false"
    @cancel="handleCancel"
  >
    <div class="notice-modal">
      <!-- 操作栏 -->
      <div class="notice-toolbar">
        <div class="toolbar-left">
          <a-button type="primary" size="small" @click="markAllAsRead">
            <template #icon><icon-check /></template>
            全部已读
          </a-button>
          <a-button 
            type="outline" 
            size="small" 
            :disabled="!selectedMessages.length"
            @click="batchDelete"
          >
            <template #icon><icon-delete /></template>
            批量删除
          </a-button>
        </div>
        <div class="toolbar-right">
          <a-button type="outline" size="small" @click="refreshMessages">
            <template #icon><icon-refresh /></template>
            刷新
          </a-button>
        </div>
      </div>

      <!-- 筛选栏 -->
      <div class="notice-filters">
        <a-row :gutter="16">
          <a-col :span="8">
            <a-input 
              v-model="queryParams.messageTitle" 
              placeholder="搜索标题" 
              allow-clear
              @change="handleSearch"
            >
              <template #prefix><icon-search /></template>
            </a-input>
          </a-col>
          <a-col :span="8">
            <a-input 
              v-model="queryParams.messageContent" 
              placeholder="搜索内容" 
              allow-clear
              @change="handleSearch"
            >
              <template #prefix><icon-search /></template>
            </a-input>
          </a-col>
          <a-col :span="4">
            <a-select 
              v-model="queryParams.messageType" 
              placeholder="消息类型" 
              allow-clear
              @change="handleSearch"
            >
              <a-option :value="0">普通消息</a-option>
              <a-option :value="1">紧急消息</a-option>
            </a-select>
          </a-col>
          <a-col :span="4">
            <a-select 
              v-model="queryParams.read" 
              placeholder="阅读状态" 
              allow-clear
              @change="handleSearch"
            >
              <a-option :value="false">未读</a-option>
              <a-option :value="true">已读</a-option>
            </a-select>
          </a-col>
        </a-row>
      </div>

      <!-- 消息列表 -->
      <div class="notice-list">
        <a-checkbox-group v-model="selectedMessages" style="width: 100%;">
          <div
            v-for="message in messageList"
            :key="message.id"
            :class="[
              'notice-item',
              { 'unread': !message.read },
              { 'urgent': message.messageType === 1 }
            ]"
          >
            <a-checkbox :value="message.id" class="notice-checkbox" />
            
            <div class="notice-content" @click="markAsRead(message)">
              <div class="notice-header">
                <span class="notice-title">{{ message.messageTitle }}</span>
                <div class="notice-meta">
                  <a-tag 
                    :color="message.messageType === 1 ? 'red' : 'blue'"
                    size="small"
                  >
                    {{ message.messageType === 1 ? '紧急' : '普通' }}
                  </a-tag>
                  <span class="notice-time">{{ formatTime(message.messageTime) }}</span>
                </div>
              </div>
              
              <div class="notice-body">
                <p class="notice-text">{{ message.messageContent }}</p>
              </div>
            </div>
            
            <div class="notice-actions">
              <a-button 
                type="outline" 
                size="small" 
                v-if="!message.read"
                @click.stop="markAsRead(message)"
                class="action-button read-button"
              >
                <template #icon><icon-check /></template>
                已读
              </a-button>
              <a-button 
                type="outline"
                size="small" 
                status="danger"
                @click.stop="deleteMessage(message)"
                class="action-button delete-button"
              >
                <template #icon><icon-delete /></template>
                删除
              </a-button>
            </div>
          </div>
        </a-checkbox-group>
        
        <!-- 空状态 -->
        <a-empty v-if="!messageList.length && !loading" description="暂无消息" />
      </div>

      <!-- 分页 -->
      <div class="notice-pagination">
        <a-pagination
          v-model:current="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :show-total="true"
          :show-jumper="true"
          :show-page-size="true"
          @change="loadMessages"
          @page-size-change="loadMessages"
        />
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { 
  getNoticeMessagesApi, 
  markAsReadApi, 
  batchMarkAsReadApi, 
  markAllAsReadApi,
  deleteMessagesApi,
  getUnreadCountApi
} from '@/api/notice'
import { formatTime } from '@/utils/format'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'update-count'])

const modalVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const loading = ref(false)
const messageList = ref([])
const selectedMessages = ref([])
const total = ref(0)

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  messageTitle: '',
  messageContent: '',
  messageType: null,
  read: null,
  orderBy: 'message_time',
  orderDirection: 'desc'
})

// 加载消息列表
const loadMessages = async () => {
  try {
    loading.value = true
    const response = await getNoticeMessagesApi(queryParams.value)
    if (response.data.code === '00000') {
      const pageResult = response.data.data
      messageList.value = pageResult.list || []
      total.value = pageResult.total || 0
    } else {
      Message.error(response.data.msg || '获取消息列表失败')
    }
  } catch (error) {
    console.error('获取消息列表失败:', error)
    Message.error('获取消息列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索消息
const handleSearch = () => {
  queryParams.value.pageNum = 1
  loadMessages()
}

// 标记单条消息为已读
const markAsRead = async (message) => {
  if (message.read) return
  
  try {
    const response = await markAsReadApi(message.id)
    if (response.data.code === '00000') {
      message.read = true
      updateUnreadCount()
      Message.success('标记成功')
    } else {
      Message.error(response.data.msg || '标记失败')
    }
  } catch (error) {
    console.error('标记已读失败:', error)
    Message.error('标记失败')
  }
}

// 批量标记为已读
const batchMarkAsRead = async () => {
  if (!selectedMessages.value.length) {
    Message.warning('请选择要标记的消息')
    return
  }
  
  try {
    const response = await batchMarkAsReadApi(selectedMessages.value)
    if (response.data.code === '00000') {
      // 更新本地状态
      messageList.value.forEach(msg => {
        if (selectedMessages.value.includes(msg.id)) {
          msg.read = true
        }
      })
      selectedMessages.value = []
      updateUnreadCount()
      Message.success(`成功标记 ${response.data.data} 条消息为已读`)
    } else {
      Message.error(response.data.msg || '批量标记失败')
    }
  } catch (error) {
    console.error('批量标记失败:', error)
    Message.error('批量标记失败')
  }
}

// 全部标记为已读
const markAllAsRead = async () => {
  try {
    const response = await markAllAsReadApi()
    if (response.data.code === '00000') {
      // 更新本地状态
      messageList.value.forEach(msg => {
        msg.read = true
      })
      updateUnreadCount()
      Message.success(`成功标记 ${response.data.data} 条消息为已读`)
    } else {
      Message.error(response.data.msg || '标记失败')
    }
  } catch (error) {
    console.error('全部标记失败:', error)
    Message.error('标记失败')
  }
}

// 删除单条消息
const deleteMessage = async (message) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这条消息吗？删除后不可恢复。',
    onOk: async () => {
      try {
        const response = await deleteMessagesApi([message.id])
        if (response.data.code === '00000') {
          const index = messageList.value.findIndex(msg => msg.id === message.id)
          if (index > -1) {
            messageList.value.splice(index, 1)
            total.value -= 1
          }
          updateUnreadCount()
          Message.success('删除成功')
        } else {
          Message.error(response.data.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除消息失败:', error)
        Message.error('删除失败')
      }
    }
  })
}

// 批量删除
const batchDelete = async () => {
  if (!selectedMessages.value.length) {
    Message.warning('请选择要删除的消息')
    return
  }
  
  Modal.confirm({
    title: '确认批量删除',
    content: `确定要删除选中的 ${selectedMessages.value.length} 条消息吗？删除后不可恢复。`,
    onOk: async () => {
      try {
        const response = await deleteMessagesApi(selectedMessages.value)
        if (response.data.code === '00000') {
          // 更新本地状态
          messageList.value = messageList.value.filter(msg => 
            !selectedMessages.value.includes(msg.id)
          )
          total.value -= response.data.data
          selectedMessages.value = []
          updateUnreadCount()
          Message.success(`成功删除 ${response.data.data} 条消息`)
        } else {
          Message.error(response.data.msg || '批量删除失败')
        }
      } catch (error) {
        console.error('批量删除失败:', error)
        Message.error('批量删除失败')
      }
    }
  })
}

// 刷新消息
const refreshMessages = () => {
  loadMessages()
}

// 更新未读数量
const updateUnreadCount = async () => {
  try {
    const response = await getUnreadCountApi()
    if (response.data.code === '00000') {
      emit('update-count', response.data.data || 0)
    }
  } catch (error) {
    console.error('获取未读数量失败:', error)
  }
}

// 关闭模态框
const handleCancel = () => {
  modalVisible.value = false
}

// 监听模态框打开，加载数据
watch(modalVisible, (visible) => {
  if (visible) {
    loadMessages()
  } else {
    // 重置选择状态
    selectedMessages.value = []
  }
})
</script>

<style scoped>
.notice-modal {
  max-height: 70vh;
  display: flex;
  flex-direction: column;
}

.notice-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--color-border-2);
}

.toolbar-left,
.toolbar-right {
  display: flex;
  gap: 8px;
}

.notice-filters {
  margin-bottom: 16px;
}

.notice-list {
  flex: 1;
  overflow-y: auto;
  max-height: 400px;
  margin-bottom: 16px;
}

.notice-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  margin-bottom: 8px;
  border: 1px solid var(--color-border-2);
  border-radius: 8px;
  transition: all 0.3s;
  cursor: pointer;
  position: relative;
  background: var(--color-bg-1);
}

.notice-item:hover {
  border-color: var(--color-primary-light-4);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transform: translateY(-1px);
}

.notice-item.unread {
  border-left: 4px solid var(--color-primary-6);
  background: linear-gradient(135deg, var(--color-primary-light-1) 0%, var(--color-bg-1) 100%);
  position: relative;
}

.notice-item.unread::before {
  content: '';
  position: absolute;
  top: 8px;
  right: 8px;
  width: 8px;
  height: 8px;
  background: var(--color-primary-6);
  border-radius: 50%;
  animation: pulse 2s infinite;
}

.notice-item.urgent {
  border-left: 4px solid var(--color-danger-6);
  background: linear-gradient(135deg, var(--color-danger-light-1) 0%, var(--color-bg-1) 100%);
  position: relative;
}

.notice-item.urgent::before {
  content: '🚨';
  position: absolute;
  top: 8px;
  right: 8px;
  font-size: 14px;
  animation: urgentBlink 1.5s infinite;
}

@keyframes pulse {
  0% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.6;
    transform: scale(1.2);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes urgentBlink {
  0%, 50% {
    opacity: 1;
  }
  25%, 75% {
    opacity: 0.5;
  }
}

.notice-checkbox {
  margin-top: 4px;
}

.notice-content {
  flex: 1;
  min-width: 0;
}

.notice-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.notice-title {
  font-weight: 500;
  font-size: 14px;
  color: var(--color-text-1);
  margin-right: 12px;
}

.notice-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.notice-time {
  font-size: 12px;
  color: var(--color-text-3);
}

.notice-body {
  color: var(--color-text-2);
}

.notice-text {
  font-size: 13px;
  line-height: 1.5;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.notice-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.action-button {
  min-width: 60px;
  transition: all 0.3s ease;
  border-radius: 6px;
}

.read-button {
  border-color: var(--color-success-6);
  color: var(--color-success-6);
}

.read-button:hover {
  background-color: var(--color-success-light-1);
  border-color: var(--color-success-5);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 180, 42, 0.2);
}

.delete-button {
  border-color: var(--color-danger-6);
  color: var(--color-danger-6);
}

.delete-button:hover {
  background-color: var(--color-danger-light-1);
  border-color: var(--color-danger-5);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(245, 63, 63, 0.2);
}

.notice-pagination {
  padding-top: 16px;
  border-top: 1px solid var(--color-border-2);
  display: flex;
  justify-content: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .notice-toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .toolbar-left,
  .toolbar-right {
    justify-content: center;
  }
  
  .notice-item {
    flex-direction: column;
    gap: 8px;
  }
  
  .notice-actions {
    flex-direction: row;
    justify-content: flex-end;
  }
}
</style>